package com.example.flower_shop.utils;

import com.example.flower_shop.common.CacheObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.TimeUnit;

public class CacheUtil {
    private static final Cache<String, CacheObject> cache = Caffeine.newBuilder()
            .maximumSize(256)
            .initialCapacity(5)
            .build();

    public static CacheObject get(String key) {
        return cache.getIfPresent(key);
    }

    public static void put(String key, String value) {
        cache.put(key, new CacheObject(value));
    }

    /**
     * @param key     缓存key
     * @param value   缓存value
     * @param timeout 超时时间 秒
     */
    public static void put(String key, String value, long timeout) {
        cache.put(key, new CacheObject(value, timeout));
    }

    /**
     * @param key      缓存key
     * @param value    缓存value
     * @param timeout  超时时间
     * @param timeUnit 时间单位
     */
    public static void put(String key, String value, long timeout, TimeUnit timeUnit) {
        switch (timeUnit) {
            case MINUTES -> timeout = timeout * 60;
            case HOURS -> timeout = timeout * 60 * 60;
            case DAYS -> timeout = timeout * 60 * 60 * 24;
            case MILLISECONDS -> timeout = timeout * 1000;
        }
        cache.put(key, new CacheObject(value, timeout));
    }

    public static void remove(String key) {
        cache.invalidate(key);
    }
}
